package com.engine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Category;

public class CSurvey implements ISerialComm{
	private ISerialComm _parent;
	private DisplayTools displayTools;
	static final Category log = Category.getInstance(CSurvey.class);
	public CSurvey(ISerialComm parent,DisplayTools displayTools)
	{
		_parent=parent;
		this.displayTools = displayTools;
		//sendResetAll();
		run();
	}
	
	private void sendReset(String layanan)
	{
		log.info("Send Reset:" + layanan);
		String cmd="S" + layanan + "NOHUS";
		_parent.sendCommand(cmd);
	}
	
	private void sendResetAll()
	{
		new Thread(new SendResetThread()).start();
	}
	
	public void run()
	{
		new Thread(new SendThread()).start();
	}

	@Override
	public boolean isPortOpen() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void sendCommand(String strCommand) {
		// TODO Auto-generated method stub
		
	}

	private String parseResponse(String resp)
	{
		/*
		if(resp.length()>10)
		{
			int start = resp.length()-10;
			String m= resp.substring(start, resp.length());
			return m;
		}
		else
			return resp;
			*/
		return resp;
	}
	
	@Override
	public void responseCommand(String strResp) {
		// TODO Auto-generated method stub
		//D01010HUS
		log.info("[CSurvey]->recv: " + strResp);
		String m_resp = parseResponse(strResp);
		log.info("[CSurvey]->parsed recv: " + m_resp);

		if(m_resp.length()<10)
		{
			return;
		}
		
		String layanan = m_resp.substring(1, 3);
		String kepuasan = m_resp.substring(3, 6);
		
		if(kepuasan.equals("000"))
		{
			return;
		}

		log.info("Layanan Survey: " + layanan);
		log.info("Kepuasan Survey: " + kepuasan);
		//save into file.
		createFile(layanan);
		saveSurvey(layanan,kepuasan);
		//say voice up.
		int iLayanan = Integer.parseInt(layanan);
		String strResponse="D" + (char)iLayanan + "UP HUS" ;
		//DUP HUS
		_parent.responseCommand(strResponse);
	}	
	
	private void saveSurvey(String layanan,String kepuasan)
	{
		SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd");
		String folder="survey\\" + sdf.format(new Date());
		folder+="\\" + kepuasan;
		boolean exists = (new File(folder)).exists();
		if(exists)
		{
			try{

	            FileWriter fstream = new FileWriter(folder,true);
	            BufferedWriter fbw = new BufferedWriter(fstream);
	            fbw.write("1");
	            fbw.newLine();
	            fbw.close();
	        }catch (Exception e) {
	            log.info("Error: " + e.getMessage());
	        }
		}
		folder="survey\\" + sdf.format(new Date());
		folder+="\\" + layanan  + "\\" + kepuasan;
		exists = (new File(folder)).exists();
		if(exists)
		{
			try{

	            FileWriter fstream = new FileWriter(folder,true);
	            BufferedWriter fbw = new BufferedWriter(fstream);
	            fbw.write("1");
	            fbw.newLine();
	            fbw.close();
	        }catch (Exception e) {
	        	log.info("Error: " + e.getMessage());
	        }
		}
	}
	private void createFile(String layanan)
	{
		SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd");
		String folder="survey";
		boolean exists = (new File(folder)).exists();
		if(!exists)
		{
			new File(folder).mkdir();
		}
		
		folder="survey\\" + sdf.format(new Date());
		exists = (new File(folder)).exists();
		if(!exists)
		{
			new File(folder).mkdir();
		}
		
		exists= (new File(folder + "\\100")).exists();
		if(!exists)
		{
			try {
				new File(folder + "\\100").createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.info(e.getLocalizedMessage());
			}
		}
		exists= (new File(folder + "\\010")).exists();
		if(!exists)
		{
			try {
				new File(folder + "\\010").createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.info(e.getLocalizedMessage());
			}
		}
		exists= (new File(folder + "\\001")).exists();
		if(!exists)
		{
			try {
				new File(folder + "\\001").createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.info(e.getLocalizedMessage());
			}
		}
		
		
		String folder1 = folder + "\\" + layanan;
		exists = (new File(folder1)).exists();
		if(!exists)
		{
			new File(folder1).mkdir();
		}
		
		exists= (new File(folder1 + "\\100")).exists();
		if(!exists)
		{
			try {
				new File(folder1 + "\\100").createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.info(e.getLocalizedMessage());
			}
		}
		exists= (new File(folder1 + "\\010")).exists();
		if(!exists)
		{
			try {
				new File(folder1 + "\\010").createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.info(e.getLocalizedMessage());
			}
		}
		exists= (new File(folder1 + "\\001")).exists();
		if(!exists)
		{
			try {
				new File(folder1 + "\\001").createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.info(e.getLocalizedMessage());
			}
		}
	}
	
	class SendThread implements Runnable{
		
		public SendThread()
		{
			
		}
		
		public void run()
		{
			int counter= displayTools.getCounter_keypad();
			int idx=0;
			//String cmd = "D[COUNTER]000HUS";
			DecimalFormat dc = new DecimalFormat("00");
			while(_parent.isPortOpen())
			{
				try {
					
					if(idx== counter)
					{
						idx=0;
					}
					
					String keyData = displayTools.getKeyData(idx);
					if ((keyData == null) || (keyData.equals("")))
			            continue;
					
					try
					{
						String cmd= "S" + dc.format(Integer.parseInt(keyData))+ "000HUS";
						_parent.sendCommand(cmd);
					}
					catch(Exception ex){}
					idx++;
					Thread.sleep(displayTools.getDelaySurvey());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
			}
		}
	}
	
	class SendResetThread implements Runnable
	{
		public void run()
		{
			log.info("Start Send Reset All Survey");
			int counter= displayTools.getCounter_keypad();
			DecimalFormat dc = new DecimalFormat("00");
			if(_parent.isPortOpen())
			{
				for(int i=0; i < counter;i++)
				{
					int iLayanan= i+1;
					String layanan =dc.format(iLayanan);
					String cmd="S" + layanan + "NOHUS";
					_parent.sendCommand(cmd);
					try {
						Thread.sleep(displayTools.getDelaySurvey());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
					}
				}
			}
			log.info("Finish Send Reset All Survey");
		}
	}
}
